package com.bsy.videostation.ui.activity

import android.os.Bundle
import android.view.KeyEvent
import com.bsy.framework.base.BaseMvvmActivity
import com.bsy.framework.ext.onClick
import com.bsy.videostation.constant.detailsUrl
import com.bsy.videostation.viewmodel.WebViewViewModel
import com.dg.videostation.databinding.ActivityWebviewBinding
import com.gyf.immersionbar.ImmersionBar
import kotlin.random.Random

class WebViewActivity : BaseMvvmActivity<ActivityWebviewBinding, WebViewViewModel>() {
    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).fullScreen(true).init()
        val index = Random.nextInt(0,detailsUrl.size - 1)
        val url = intent.getStringExtra("url")
        val  realUrl = if (url.isNullOrEmpty()) detailsUrl[index] else url
        mBinding.webView.loadUrl(realUrl)
    }

    override fun initListener() {
        mBinding.ivBack.onClick {
            if (mBinding.webView.canGoBack())
                mBinding.webView.goBack()// 返回前一个页面
            else
                finish()
        }
    }

    // 覆盖onKeydown 添加处理WebView 界面内返回事件处理
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mBinding.webView.canGoBack()) {
            mBinding.webView.goBack()// 返回前一个页面
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onResume() {
        super.onResume()
        mBinding.webView.onResume()
        pauseAllVideos()
    }

    private fun pauseAllVideos() {
        val jsCode = """
        javascript:(function() {
            var videos = document.getElementsByTagName('video');
            for (var i = 0, len = videos.length; i < len; i++) {
                videos[i].pause();
            }
        })();
    """
        mBinding.webView.evaluateJavascript(jsCode, null)
    }

    override fun onPause() {
        super.onPause()
        mBinding.webView.onPause()
    }

    override fun onDestroy() {
        mBinding.webView.destroy()
        super.onDestroy()
    }
}